<script setup lang="ts" name="Account">
import dayjs from "dayjs";
import API from "@/api";
import { nocache, userinfo } from "@/store";
import { numberDigits, typeDigits } from "@/const/color";
const global: any = getCurrentInstance()?.appContext.config.globalProperties;
const { t } = useI18n();

const route = useRoute();
const router = useRouter();
const images = reactive({
  expand: new URL("@/assets/images/Result/expand.png", import.meta.url).href,
  arrow: new URL("@/assets/images/Result/arrow.png", import.meta.url).href,
  reward: new URL("@/assets/images/Result/reward.png", import.meta.url).href,
});

const piniaNocache = nocache();
const piniaUserinfo: any = userinfo();

const data: any = reactive({
  currentLotteryId: 1,
  tabList: [
    { text: computed(() => t("result.test14")), value: 1 },
    { text: computed(() => t("result.test15")), value: 2 },
    {text: computed(() => t('result.test18')), value: 4 },
    {text: computed(() => t('result.test19')), value: 3 },
  ],
  currentTypeId: 0,
  drawIndex: 0,
  showTypePicker: false,
  drawList: [
    {
      name: computed(() => t("mybet.state4")),
    },
    {
      name: computed(() => t("mybet.state1")),
    },
  ],
  lotteryList: [],
  typeList: [],
  pagination: {
    loading: false,
    pageNum: 1,
    pageSize: 10,
    total: 0,
  },
  showLotteryTypePicker: false,
  lotteryTypeList: [],
});

const {
  currentLotteryId,
  tabList,
  currentTypeId,
  drawList,
  drawIndex,
  lotteryList,
  pagination,
  typeList,
  showTypePicker,
  showLotteryTypePicker,
  lotteryTypeList,
} = toRefs(data);
const queryPlanList = () => {
  API.planListAPI({ typeConfigCode: currentLotteryId.value }).then(
    (res: any) => {
      handlePlanList(res);
    }
  );
};

const changeLang = () => {
  lotteryTypeList.value = lotteryTypeList.value.map((item: any) => {
    if (item?.children) {
      const current = item.children?.find(
        (im: any) => im.languageCode == piniaUserinfo.getLang.languageCode
      );
      if (current) {
        return {
          ...item,
          url: current?.url,
          lotteryTypeName: current.title,
        };
      }
    }
  });
};
watch(
  () => piniaUserinfo.getLang,
  (val, preVal) => {
    changeLang();
  },
  { immediate: false, deep: true }
);
const queryLotteryList = async () => {
  let res = await API.lotteryType({});
  if (res.code === 200) {
    lotteryTypeList.value = res.data;
    changeLang();
  }
};
queryLotteryList();

const comtabList = computed(() => {
  let lotteryTypeListMap = lotteryTypeList.value.map((it: any) => {
    return {
      text: it?.lotteryTypeName,
      value: it?.code,
    };
  });
  return [...tabList.value, ...lotteryTypeListMap];
});

const getMyLotteryList = () => {
  pagination.value.loading = true;
  API.getMyOrderList({
    pageNum: pagination.value.pageNum,
    pageSize: pagination.value.pageSize,
    planId: currentTypeId.value,
    state: +drawIndex.value + 1,
    typeConfigCode: currentLotteryId.value,
  })
    .then((res) => {
      if (res?.code === 200 && res?.rows) {
        lotteryList.value = [...lotteryList.value, ...res.rows];
        if (currentLotteryId.value != 1 || currentLotteryId.value != 2) {
          //处理时彩和pick10传数据格式
          lotteryList.value.forEach((item: any) => {
            item.contentList = JSON.parse(item.content);
          });
        }
        pagination.value.total = res?.total || 0;
      }
    })
    .finally(() => {
      pagination.value.loading = false;
    });
};
const currentLotteryName = computed(() => {
  return comtabList.value?.find((it: any) => it.value == currentLotteryId.value)
    ?.text;
});
const currentTypeName = computed(() => {
  return typeList.value?.find((it: any) => it.value == currentTypeId.value)
    ?.text;
});

watch(
  () => piniaNocache.getHitBottom,
  () => {
    let totalPage = Math.ceil(
      pagination.value.total / pagination.value.pageSize
    );
    if (pagination.value.pageNum < totalPage) {
      pagination.value.pageNum++;
      getMyLotteryList();
    }
  }
);

const handlePlanList = (res: any) => {
  if (res.code == 200) {
    typeList.value = [
      { text: computed(() => t("mybet.all")), value: 0 },
      ...res.data,
    ];
    typeList.value = typeList.value.map((item: any) => {
      return {
        ...item,
        text: item.planName || item.text,
        value: item.id || item.value,
      };
    });
    currentTypeId.value = typeList.value[0].value;
    handleTypeItem([typeList.value[0]]);
  }
};

const handleLotteryItem = (item: any) => {
  currentLotteryId.value = item[0].value;
  showLotteryTypePicker.value = false;
  const queryUrl = useUrlSearchParams();
  router.push({
    path: "/me/account",
    query: { ...queryUrl, type: item[0].value },
  });
};
const handleTypeItem = (item: any) => {
  currentTypeId.value = item[0].value;
  lotteryList.value = [];
  showTypePicker.value = false;
  pagination.value.pageNum = 1;
  getMyLotteryList();
};
const handleDraw = (index: number) => {
  drawIndex.value = index;
  lotteryList.value = [];
  pagination.value.pageNum = 1;
  const queryUrl = useUrlSearchParams();
  router.push({ path: "/me/account", query: { ...queryUrl, tab: index } });
  getMyLotteryList();
};
const statusFunc = (state: any) => {
  switch (state) {
    case 1:
      return t("mybet.state4");
    case 2:
      return t("mybet.state2");
    case 3:
      return t("mybet.state7");
    case 4:
      return t("mybet.state5");
    case 5:
      return t("mybet.state6");
  }
};

const handleReceive = (id: number) => {
  let params = {
    id,
    type: currentLotteryId.value,
  };
  API.receiveAPI(params).then((res) => {
    if (res.code === 200) {
      global.message(t("mybet.text2"));
      lotteryList.value = [];
      pagination.value.pageNum = 1;
      getMyLotteryList();
    }
  });
};
const handleShowSelect = () => {
  showTypePicker.value = true;
};
const handleShowLottery = () => {
  showLotteryTypePicker.value = true;
};
const goPrivateOrder = (item: any) => {
  if (currentLotteryId.value == 1 || currentLotteryId.value == 2) return;
  router.push({ path: "/viewPrivateOrder", query: item });
};
const goLastPage = () => {
  router.push("/me");
};

const renderRegGreen = (listStr: string) => {
  if (typeof listStr === "string") {
    let list = JSON.parse(listStr);
    list.length = 3;
    let radiusDom = list.map((it: any) => {
      const str = it?.content?.split("_");
      let fristNum = str[0];
      let thirdNum = str[2];
      let bg;
      if (+fristNum == 1) {
        bg = typeDigits.find((it: any) => {
          return it.id == +thirdNum;
        })?.bg;
      } else {
        bg = numberDigits.find((it: any) => {
          return it.id == +thirdNum;
        })?.bg;
      }
      return {
        bg,
        number: +fristNum == 1 ? "" : thirdNum,
      };
    });
    return radiusDom;
  }
  return [];
};

const renderSix = (listStr: string) => {
  let types = ["猪", "羊", "狗", "牛", "虎", "蛇", "蛇"];
  if (typeof listStr === "string") {
    let list = JSON.parse(listStr);
    list.length = 3;
    let radiusDom = list.map((it: any, index: number) => {
      const str = it?.content?.split("_");
      let thirdNum = str[2];
      return {
        type: types[index],
        number: thirdNum,
      };
    });
    return radiusDom;
  }
  return [];
};
const getContent = (content:any) => {
  let data = JSON.parse(content)
  let betContent:any = []
  data.forEach((item:any) => {
    betContent.push(item.name)
  })
  let showContent
  if (betContent.length > 1) {
    showContent = betContent[0].toString() + '....'
  } else {
    showContent = betContent[0].toString()
  }
  return showContent
}
watch(
  [() => currentTypeId.value, () => currentLotteryId.value],
  ([val1, val2]) => {
    lotteryList.value = [];
  }
);
watch(
  () => route?.query?.type,
  (val, oldVal) => {
    if (val && val != oldVal) {
      currentLotteryId.value = val;
      queryPlanList();
    }
  },
  {
    immediate: true,
  }
);
watch(
  () => route?.query?.tab,
  (val) => {
    if (val) {
      drawIndex.value = val;
    }
  },
  {
    immediate: true,
  }
);
</script>

<template>
  <div class="accountPage">
    <DetailHeader
      :title="t('mybet.text3')"
      :isNeedBackIcon="true"
      @goBackPage="goLastPage"
      :isNeedRedirectPage="true"
    />
    <div class="resultContainer">
      <div class="tabContainer"></div>
      <div>
        <div class="topData">
          <div class="isLotteryDraw">
            <div
              class="drawItem"
              v-for="(el, index) in drawList"
              :key="index"
              @click="handleDraw(index)"
              :class="{ activeDraw: +drawIndex === index }"
            >
              {{ el.name }}
            </div>
          </div>
          <div class="type">
            <div class="typeData" @click="handleShowLottery">
              <div class="typeTitle">{{ t("mybet.title1") }}</div>
              <div class="typeItem">{{ currentLotteryName }}</div>
            </div>
          </div>
          <div class="type">
            <div class="typeData" @click="handleShowSelect">
              <div class="typeTitle">{{ t("mybet.title2") }}</div>
              <div class="typeItem">{{ currentTypeName }}</div>
            </div>
          </div>
          <!-- 彩种下拉 -->
          <PopSelect
            v-model:showPicker="showLotteryTypePicker"
            :columns="comtabList"
            @onConfirmSelect="handleLotteryItem"
            :curentId="+currentLotteryId"
            :title="t('mybet.text1')"
          />
          <!-- 类型下拉 -->
          <PopSelect
            v-model:showPicker="showTypePicker"
            :columns="typeList"
            @onConfirmSelect="handleTypeItem"
            :curentId="+currentTypeId"
          />
        </div>
      </div>
    </div>
    <div class="lotteryList">
      <div class="listItem" v-for="(it, index) in lotteryList" :key="index">
        <div class="titleTop">
          {{ it.lotteryClassName }} <span>{{ it.period }}</span>
        </div>
        <div
          class="tikets"
          v-if="
            it.bigCode == 1 ||
            it.bigCode == 2 ||
            it.bigCode == 3 ||
            it.bigCode == 4 ||
            it.bigCode == 5 ||
            it.bigCode == 6
          "
          @click="goPrivateOrder(it)"
        >
          {{ t("mybet.text4") }}
          <div v-if="it.bigCode == 4" class="detailRedGreen">
            <span
              v-for="(itCont, index) in renderRegGreen(it.content)"
              :key="index"
              class="radius"
              :style="{
                background: itCont?.bg,
              }"
              >{{ itCont?.number }}</span
            >
            &nbsp;
          </div>
          <div
            v-else-if="it.bigCode == 5"
            class="detailsix"
            v-for="(itCont, index) in renderSix(it.content)"
            :key="index"
          >
            <p>{{ itCont.number }}</p>
            <p>{{ itCont.type }}</p>
          </div>
          <div
            v-else-if="it.bigCode == 6"
          >
            <p>{{ getContent(it.content) }}</p>
          </div>
        </div>
        <div class="tikets" v-else>
          {{ t("mybet.text4") }}
          <p class="detailRow">{{ it.content }}</p>
        </div>
        <div class="Drawdate">
          {{ t("mybet.text5") }}
          <p class="detailRow">
            {{ dayjs(+it.createTime).format("DD-MM-YYYY hh:mm A") }}
          </p>
        </div>
        <div class="PickUP" v-if="it.state == 3" @click="handleReceive(it.id)">
          {{ statusFunc(it.state) }}
        </div>
        <div class="notPickUP PickUP" v-else>{{ statusFunc(it.state) }}</div>
        <div class="money" v-if="it.winMoney > 0">₹{{ it.winMoney }}</div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import url("./index.scss");
</style>
